var Ajax = jQuery;
Ajax.call = function (url, params, callback, transferMode, responseType, asyn, quiet){
    this.ajax({
        url: url+'&t='+Math.random()+'&is_ajax',
        async: asyn,
        data: params,
        type: transferMode,
        dataType: responseType,
        success: callback
    });
};
function delete_cart_product(shop_id, obj) {
    var num = $(obj).attr('num');
    Ajax.call('/index.php?app_act=index/delete_cart_product','app_fmt=json&app_page=null&id='+shop_id,function(data) {
        data=eval('('+data+')');
        if(data.code ==0) {
            $(obj).parents('li').remove();
            var cart_num = parseInt($("#cart_num").html());
            $("#cart_num").html(cart_num-num);
        }
    }, 'POST', '')
}
function changhb(bizhong)
{
    $.cookie('currency_cod',bizhong, {expires: 7, path: '/'});
    $(".g_bizhong_s").html(bizhong);
    $("span[name='price_mark']").html(bizhong);
    $("span[name='price_num'][orgp]").each(function(i,o){
        var yuanshi = $(this).attr('orgp');
        $(this).html((parseFloat(my_array[$.cookie('currency_cod')]) * parseFloat(yuanshi)).toFixed(2));
    });
}




function page_ajax(page,url,div) {
    var params ="page="+page+"&ajax_url="+encodeURIComponent(url,'UTF-8')+"&ajax_div="+div;
    Ajax.call(url, params,
        function (s){
            if(s !='') {
                $("#"+div).html(s);
                if($("#"+div).css('display') =='block' || $("#"+div).css('display') =='') {
                    $("#"+div).show();
                }else {
                    $("#"+div).hide();
                }
            }else{
                $("#"+div).hide();
            }
        }, 'POST', '');
}
function page_ajax_load(page,url,div) {
    var params ="page="+page+"&ajax_url="+encodeURIComponent(url,'UTF-8')+"&ajax_div="+div;
    Ajax.call(url, params,
        function (s){
            if(s !='') {
                $("#"+div).html(s);
            }else{
                $("#"+div).html('');
            }
        }, 'POST', '');
}
function page_ajax_res(page,url,div) {
    var params ="page="+page+"&ajax_url="+encodeURIComponent(url,'UTF-8')+"&ajax_div="+div;
    Ajax.call(url, params,
        function (s){
            if(s !='') {
                $("#"+div).html(s);
                if($("#"+div).css('display') =='block' || $("#"+div).css('display') =='') {
                    $("#"+div).show();
                }else {
                    $("#"+div).hide();
                }
            }else{
                $("#"+div).hide();
            }
        }, 'POST', '');
}
function ajaxcheck(objname,checkurl,param,action,type){
    Ajax.call(checkurl, param,
        function (s){
            s=eval('('+s+')');
            if(s.code ==0) {
                if( type == 'order' ){
                    window.top.location = '/orders/';
                }else{
                    //window.top.location = '/carts/add?'+Math.random();
                    location.href = '/carts.html?'+Math.random();
                }
            }else {
                if(action=='second'){
                    $('#vCode').attr('src','/index.php?app_act=printpic/do_index&type=spike&'+ Math.random());
                }
                alert(s.msg);
            }
        }
        , 'POST', '');
}
var $app_url = 'index.php?app_act=';
function showErrors(){
    var t = this;
    for ( var i = 0; this.errorList[i]; i++ ) {
        var error = this.errorList[i];
        this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
        var elename = this.idOrName(error.element);
        var obj = jQuery('#check'+elename);
//        if(obj.parent().parent().hasClass('right')){
//            obj.parent().parent().removeClass('right') ;
//        }
//        obj.parent().parent().addClass('error') ;
        obj.html('');
        obj.show();
        var errsdiv = jQuery('span[htmlfor='+ elename + ']');
        if(errsdiv.length == 0){
            errsdiv = jQuery('<span class="error_img" id="errmsg'+elename+'"></span>');
            errsdiv.attr({"for":  this.idOrName(error.element), generated: true});
            errsdiv.appendTo(jQuery('#check'+elename));
        }
        errsdiv.html(error.message || "");
    }

    // 校验成功的去掉错误提示
    for ( var i = 0; this.successList[i]; i++ ) {
        if(this.idOrName(this.successList[i])=='nickname'|| this.idOrName(this.successList[i])=='email'){
            timeout = setTimeout("showRight('"+ this.idOrName(this.successList[i]) +"')",1000);
        }else{
            showRight(this.idOrName(this.successList[i]));
        }
    }
}
function showRight(dd){
    jQuery('#check'+dd).parent().parent().addClass('right') ;
    jQuery('#check'+dd).html('');
    jQuery('#check'+dd).show();
}
function countByteLength(str, cnCharByteLen){
    var byteLen = 0;
    for (var i=0; i<str.length; i++){
        if ((/[\x00-\xff]/g).test(str.charAt(i)))
            byteLen += 1;
        else
            byteLen += cnCharByteLen;
    }
    return byteLen;
}
//base64加密函数
function base64encode(str) {
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var base64DecodeChars = new Array(
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
        -1,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
        -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
    var out, i, len;
    var c1, c2, c3;

    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if(i == len)
        {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if(i == len)
        {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
        out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}
//获取URL参数
function request(paras){
    var url = location.href;
    var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
    var paraObj = {}
    for (i=0; j=paraString[i]; i++){
        paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if(typeof(returnValue)=="undefined"){
        return "";
    }else{
        return returnValue;
    }
}
//共用tab选项卡
//tab切换
function tabFun(tab,content,current){
    var conNum = 0;
    $(tab).click(function(){
        $(this).addClass(current).siblings().removeClass(current);
        conNum =$(this).index();
        $(content).eq(conNum).show().siblings().hide();
    });
}
function web_search() {
    var key_search = $("input[name='key_search']").val();
    if(key_search !='') {
        location.href = '/search-'+ (encodeURI(key_search,'utf-8'))+'.html';
    } else {
        location.href = '/search-0.html';
    }
    return false;
}
function redirect_search(obj) {
    var key_search = $(obj).siblings('input').val();
    if(key_search) {
        key_search = (encodeURI(key_search,'utf-8'));
    }
    location.href = '/brandsearch-0-0-0-'+key_search+'.html';
}
function fast_login(act) {
    $("#formLogin").validate({
        event: "blur",
        rules: {
            username:{
                required: true
            },
            password:{
                required: true,
                string:true,
                minlength: 6,
                maxlength:16
            }
        },
        messages : {
            username:{
                required: 'Must be not empty'
            },
            password: {
                required: "The password must be not empty",
                minlength: jQuery.validator.format("The length of the password must be over {0}")
            }
        },
        focusInvalid: false,
        onkeyup: false,
        showErrors: showErrors,
        submitHandler: function(form){
            var params="app_fmt=json&user_name="+base64encode(encodeURI($('#username').val(),'utf-8'))
                +"&password="+base64encode($('#password').val());
            Ajax.call('/index.php?app_act=user/index/do_login', params,
                function (s){
                    s = eval('(' + s + ')');
                    switch(s['statusCode']){
                        case 0:
                            if(act=='spikes' || act=='goods'){
                                location.reload();
                            }else{
                                $.get("/index.php?app_act=index/get_user_info&"+ Math.random(),"",function(data){$('#login_info').html(data)},"html");
                            }
                            break;
                        case 1:
                        case -110:
                            $("#checkusername").addClass('error').html(s['status']);
                            break;
                        case -120:
                            $("#checkpassword").addClass('error').html(s['status']);
                            break;
                        default:
                            break;
                    }
                }
                , 'POST', 'JSON');
        }
    });
}

function checkCardId(socialNo){
    if(socialNo == "")  {
        alert("输入身份证号码不能为空!");
        return (false);
    }

    if (socialNo.length != 15 && socialNo.length != 18)
    {
        alert("输入身份证号码格式不正确!");
        return (false);
    }
    var area={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};

    if(area[parseInt(socialNo.substr(0,2))]==null) {
        alert("身份证号码不正确(地区非法)!");
        return (false);
    }

    if (socialNo.length == 15)
    {
        pattern= /^\d{15}$/;
        if (pattern.exec(socialNo)==null){
            alert("15位身份证号码必须为数字！");
            return (false);
        }
        var birth = parseInt("19" + socialNo.substr(6,2));
        var month = socialNo.substr(8,2);
        var day = parseInt(socialNo.substr(10,2));
        switch(month) {
            case '01':
            case '03':
            case '05':
            case '07':
            case '08':
            case '10':
            case '12':
                if(day>31) {
                    alert('输入身份证号码不格式正确!');
                    return false;
                }
                break;
            case '04':
            case '06':
            case '09':
            case '11':
                if(day>30) {
                    alert('输入身份证号码不格式正确!');
                    return false;
                }
                break;
            case '02':
                if((birth % 4 == 0 && birth % 100 != 0) || birth % 400 == 0) {
                    if(day>29) {
                        alert('输入身份证号码不格式正确!');
                        return false;
                    }
                } else {
                    if(day>28) {
                        alert('输入身份证号码不格式正确!');
                        return false;
                    }
                }
                break;
            default:
                alert('输入身份证号码不格式正确!');
                return false;
        }
        var nowYear = new Date().getYear();
        if(nowYear - parseInt(birth)<15 || nowYear - parseInt(birth)>100) {
            alert('输入身份证号码不格式正确!');
            return false;
        }
        return (true);
    }

    var Wi = new Array(
        7,9,10,5,8,4,2,1,6,
        3,7,9,10,5,8,4,2,1
    );
    var   lSum        = 0;
    var   nNum        = 0;
    var   nCheckSum   = 0;

    for (i = 0; i < 17; ++i)
    {


        if ( socialNo.charAt(i) < '0' || socialNo.charAt(i) > '9' )
        {
            alert("输入身份证号码格式不正确!");
            return (false);
        }
        else
        {
            nNum = socialNo.charAt(i) - '0';
        }
        lSum += nNum * Wi[i];
    }


    if( socialNo.charAt(17) == 'X' || socialNo.charAt(17) == 'x')
    {
        lSum += 10*Wi[17];
    }
    else if ( socialNo.charAt(17) < '0' || socialNo.charAt(17) > '9' )
    {
        alert("输入身份证号码格式不正确!");
        return (false);
    }
    else
    {
        lSum += ( socialNo.charAt(17) - '0' ) * Wi[17];
    }



    if ( (lSum % 11) == 1 )
    {
        return true;
    }
    else
    {
        alert("输入身份证号码格式不正确!");
        return (false);
    }

}

var country = 0;
var city=0;
var province=0;
function choose_country(obj){
    var country=$(obj).val();
    Ajax.call('/index.php?app_act=index/get_province&app_page=null&app_fmt=json&country='+country, '',
        function (s){
            var option="<option value='0'>Please select...city</option>";
            if(s.length > 0) {
                for(i=0;i<s.length;i++){
                    option+="<option value='"+s[i].id+"'>"+s[i].name+"</option>";
                }
                $('#province').html(option).show();
            }else {
                $("#province").hide();
            }

        }	, 'POST', 'json');
}
function choose_province(obj){
    var pro_text = $(obj).find('option:selected').html();
    if(pro_text != '') {
        $("#province_text").val(pro_text).attr('readonly', true);
    }
}

function choose_city(obj){
    region=$(obj).val();
}